package top.caoayu.base.controller;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.web.bind.annotation.*;
import top.caoayu.base.entity.SysUser;
import top.caoayu.base.mapper.SysRoleMapper;
import top.caoayu.base.mapper.SysUserMapper;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;

@RestController
@Api(tags = "用户管理1")
@RequestMapping("/sysUser")
public class SySUserController {
    @Resource
    private SysUserMapper sysUserMapper;
    @Resource
    private SysRoleMapper sysRoleMapper;


    @GetMapping("/{id}")
    @ApiOperation("根据id查询用户及角色权限12")
    public SysUser selectById(@PathVariable Long id){
        SysUser sysUser = sysUserMapper.selectUserRoleAndPrivilegeById(id);
//        return null;
        return sysUser;
    }
    @GetMapping("/")
    @ApiOperation("查询所有用户")
    public List<SysUser> selectAll(){
        System.out.println(1234);
        List<SysUser> sysUsers = sysUserMapper.selectAll();
        return sysUsers;
    }
    @PostMapping("/export")
    @ApiOperation("导出所有用户")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id",value = "用户id",required = true,type = "Long"),
            @ApiImplicitParam(name = "name",value = "姓名",required = true,type = "String")
    })
    public void export(HttpServletResponse response) throws IOException {
        List<SysUser> sysUsers = sysUserMapper.selectAll();
        ExportParams params = new ExportParams();
        Workbook sheets = ExcelExportUtil.exportExcel(params, SysUser.class, sysUsers);
        //Set the format of the return stream to avoid garbled code
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
// Here is urlencoder Encode can prevent Chinese garbled code. Of course, it has nothing to do with easyexcel
        String fileName = URLEncoder.encode("导出", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");

//The last return is written into the return stream
        sheets.write(response.getOutputStream());
    }
}
